<template>
  <custom-dialog
    ref="dialog"
    :title="modalTitle"
    width="640px"
    :before-confirm="beforeConfirm" :on-confirm="onConfirm"
  >
    <el-form ref="form" :model="info" :rules="rules" label-width="80px">
      <el-form-item label="用户名" prop="userName">
        <el-input v-model="info.userName" @input="onUserNameChange"></el-input>
      </el-form-item>

      <el-form-item label="登录账号" prop="loginName">
        <el-input v-model="info.loginName"></el-input>
      </el-form-item>
      <el-form-item label="账号类型" prop="accountType">
        <el-select v-model="info.accountType" class="width-100">
          <el-option value="1" label="政府端"></el-option>
          <el-option value="2" label="企业端"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="info.phone"></el-input>
      </el-form-item>
      <el-form-item label="头像" prop="profilePhotoFile" :class="{'has-profile': hasProfile}">
        <el-upload
          ref="upload"
          :auto-upload="false"
          action="#"
          :limit="1"
          list-type="picture-card"
          :file-list="fileList"
          :on-change="profilePhotoChange"
          :multiple="false"
          :upload-disabled="false"
        >
          <i slot="default" class="el-icon-plus"></i>
          <div slot="file" slot-scope="{file}">
            <img
              :src="file.url"
              alt="" class="el-upload-list__item-thumbnail"
            >
            <div class="el-upload-list__item-actions">
              <span
                class="el-upload-list__item-delete"
                @click="handleRemove(file)"
              >
                <i class="el-icon-delete"></i>
              </span>
            </div>
          </div>
        </el-upload>
      </el-form-item>
      <el-form-item v-if="info.accountType === '2'" label="所属企业" prop="tenantId">
        <el-select v-model="info.tenantId" filterable clearable class="width-100" @change="onChange">
          <el-option v-for="item in tenantIdOptions" :key="item.value" v-bind="item"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="info.email"></el-input>
      </el-form-item>
    </el-form>
  </custom-dialog>
</template>

<script>
import debounce from 'lodash/debounce'
import { saveOrUpdateUser } from '@/api/sysUser'
import CustomDialog from '@/components/custom-dialog'
import { getListEnterprise } from '@/api/enterprose'
import { upload } from '@/api/minio'
import REGEXP from '@/utils/regexp'

const api = { saveOrUpdateUser }
export default {
  name: 'operate-modal',
  props: {
    modalTitle: String,
    data: {
      type: Object,
      default () {
        return {}
      }
    }
  },
  components: {
    CustomDialog,
  },
  data () {
    return {
      tenantIdOptions: [],
      info: {
        id: '',
        userName: '',
        phone: '',
        email: '',
        loginName: '',
        accountType: '',
        profilePhoto: '',
        profilePhotoName: '',
        profilePhotoFile: null,
        tenantId: '',
        tenantName: '',
      },
      rules: {
        userName: [{ required: true, message: '请输入姓名' }],
        phone: [
          { required: true, message: '请输入手机号' },
          { pattern: REGEXP.PHONE_NUMBER, message: '请输入正确的手机号' }
        ],
        accountType: [{ required: true, message: '请选择账号类型' }],
        loginName: [{ required: true, message: '请输入登录账号' }],
        tenantId: [{ required: true, message: '请选择所属企业' }],
        email: [{ pattern: REGEXP.EMAIL, message: '请输入正确的邮箱' }]
      }
    }
  },
  computed: {
    fileList () {
      const { profilePhoto, profilePhotoName } = this.info
      return profilePhoto ? [{ name: profilePhotoName, url: profilePhoto }] : []
    },
    hasProfile () {
      const info = this.info
      return !!info.profilePhoto || !!info.profilePhotoFile
    },
  },
  created () {
    this.onUserNameChange = debounce(this.onUserNameChange)
  },
  watch: {
    'info.accountType': function () {
      if (this.$refs.dialog && this.$refs.dialog.updateScrollbar) {
        this.$refs.dialog.updateScrollbar();
      }
    }
  },
  methods: {
    profilePhotoChange (file) {
      this.info.profilePhotoFile = file.raw
    },
    handleRemove (file) {
      this.info.profilePhoto = ''
      this.info.profilePhotoName = ''
      this.info.profilePhotoFile = null
      this.$refs.upload.clearFiles()
    },
    uploadFile (file) {
      return new Promise((resolve) => {
        if (file instanceof File) {
          upload(file).then(res => {
            if (res.code === 200) {
              resolve(res.data)
            }
          }).catch(() => {
            this.$refs.dialog.saving = false
          })
        } else if (typeof file === 'object' && file.url) {
          resolve(file)
        }
      })
    },
    getOptions () {
      return getListEnterprise().then(res => {
        if (res.code === 200) {
          res.data = res.data || []
          this.tenantIdOptions = res.data.map(v => ({
            label: v.enterpriseName,
            value: v.id,
          }))
        }
      })
    },
    open () {
      const isAdd = Object.keys(this.data).length === 0
      this.info = isAdd
        ? this.$options.data().info
        : {
            ...this.$options.data().info,
            ...this.data
          }
      if (this.$refs.form) {
        this.$refs.form.resetFields()
      }
      if (this.$refs.upload) {
        this.$refs.upload.clearFiles()
      }
      if (this.info.profilePhoto) {
        this.info.profilePhotoFile = { name: this.info.profilePhotoName, url: this.info.profilePhoto }
      }
      this.getOptions()
      this.$nextTick(() => {
        this.$refs.dialog.open()
      })
    },
    beforeConfirm () {
      return this.$refs.form.validate()
    },
    saveOrUpdateUser (params, close) {
      return api.saveOrUpdateUser(params).then((res) => {
        if (res.code === 200) {
          this.$emit('save-success')
          this.$message.success('保存成功')
          close()
        }
      })
    },
    onConfirm (close) {
      const file = this.info.profilePhotoFile
      const params = { ...this.info }

      if (!params.id) {
        delete params.id
      }
      if (file) {
        return this.uploadFile(file).then((data) => {
          params.profilePhoto = data.url
          params.profilePhotoName = data.urlName || data.name
          this.saveOrUpdateUser(params, close)
        })
      } else {
        return this.saveOrUpdateUser(params, close)
      }
    },
    onRemove () {
      this.info.profilePhoto = ''
      this.info.profilePhotoName = ''
    },
    onUpload (data) {
      this.info.profilePhoto = data.url
      this.info.profilePhotoName = data.urlName
    },
    onUserNameChange (userName) {
      // this.info.loginName = this.$pinyin(userName)
      this.info.loginName = userName
    },
    onChange () {
      const tenantIdOptions = this.tenantIdOptions
      const tenantId = this.info.tenantId
      const target = tenantIdOptions.find(v => v.value === tenantId)
      if (target) {
        this.info.tenantName = target.label
      }
    },
  }
}
</script>

<style scoped>
.has-profile ::v-deep .el-upload {
  display: none;
}
</style>
